package com.huijiet.base.interceptor;


import com.huijiet.base.auth.JWTFactory;
import com.huijiet.base.auth.JWTInfo;
import com.huijiet.base.exception.NoTokenException;
import com.huijiet.base.utils.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthInterceptor implements HandlerInterceptor{

    @Resource
    private JWTFactory jwtFactory;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String authorization = request.getHeader("Authorization");
        if(StringUtil.isEmpty(authorization)){
            authorization = request.getParameter("Authorization");
        }
        if(StringUtil.isEmpty(authorization)){
            throw new NoTokenException();
        }
        JWTInfo jwtInfo = jwtFactory.validateAndGet(authorization);

        //将用户的jwtInfo保存到当前线程中
        JWTInfo.set(jwtInfo);
        return true;
    }
}
